//Refactored 
package com.example.sleepdebtcalculatorandroid;

import com.example.sleepdebtcalculatorandroid.R.id;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class IdealSleepAmountActivity extends Activity implements View.OnClickListener{

	private DatabaseHelper dbHelper;
	private TimePicker timePicker;
	private String[] SELECT = {"id", "idealSleepAmountHours", "idealSleepAmountMinutes"};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ideal_sleep_amount);
		timePicker = (TimePicker)findViewById(R.id.timePicker1);
		timePicker.setIs24HourView(true);
		dbHelper = new DatabaseHelper(this);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = ShowDATA();
		ShowDATA(cursor);
		Button enterIdealSleepAmount = (Button)findViewById(id.enterIdealSleepAmount);
		enterIdealSleepAmount.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		try{
			SQLiteDatabase db = dbHelper.getReadableDatabase();
			clearDATA();
			AddDATA();
			Cursor cursor = ShowDATA();
			ShowDATA(cursor);
		}
		finally{
			dbHelper.close();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_ideal_sleep_amount, menu);
		return true;
	}
	
	private void AddDATA(){
		
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues datas = new ContentValues();
		datas.put("idealSleepAmountHours", timePicker.getCurrentHour());
		datas.put("idealSleepAmountMinutes", timePicker.getCurrentMinute());
		db.insert("idealSleepAmount", null, datas);
	}
	
	private Cursor ShowDATA() {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query("idealSleepAmount", SELECT, null, null, null, null, null);
		return cursor;
	}
	
	private void ShowDATA(Cursor cursor) {
		StringBuilder builder = new StringBuilder("Current Ideal Sleep Amount: \n");
		while(cursor.moveToNext()){
			String idealSleepAmountHours = cursor.getString((cursor.getColumnIndex("idealSleepAmountHours")));
			String idealSleepAmountMinutes = cursor.getString((cursor.getColumnIndex("idealSleepAmountMinutes")));
			String idealSleepAmount = idealSleepAmountHours + " Hours and " + idealSleepAmountMinutes + " Minutes";
			builder.append(idealSleepAmount).append("\n");
			}
		TextView text = (TextView)findViewById(R.id.currentIdealSleepAmount);
		text.setText(builder);
	}

	private void clearDATA() {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		String deleteRows = "DELETE FROM idealSleepAmount;";
		db.execSQL(deleteRows);
	}
}
